<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 格式化时间
 * @param int|string $time 时间戳或日期字符串
 * @param string $format 格式化格式
 * @return string
 */
function format_time($time, $format = 'Y-m-d H:i:s')
{
    if (is_numeric($time)) {
        return date($format, $time);
    } else {
        return date($format, strtotime($time));
    }
}

/**
 * 获取友好的时间显示
 * @param int|string $time 时间戳或日期字符串
 * @return string
 */
function friendly_time($time)
{
    if (is_numeric($time)) {
        $timestamp = $time;
    } else {
        $timestamp = strtotime($time);
    }
    
    $diff = time() - $timestamp;
    
    if ($diff < 60) {
        return '刚刚';
    } elseif ($diff < 3600) {
        return floor($diff / 60) . '分钟前';
    } elseif ($diff < 86400) {
        return floor($diff / 3600) . '小时前';
    } elseif ($diff < 2592000) {
        return floor($diff / 86400) . '天前';
    } else {
        return format_time($timestamp, 'Y-m-d');
    }
}

/**
 * 生成分页HTML
 * @param int $total 总记录数
 * @param int $page 当前页码
 * @param int $size 每页显示数量
 * @param string $url 分页URL（不含页码参数）
 * @return string
 */
function build_pagination($total, $page = 1, $size = 10, $url = '')
{
    $total_page = ceil($total / $size);
    if ($total_page <= 1) return '';
    
    $url = $url ?: request()->baseUrl();
    $html = '<div class="pagination">';
    
    // 上一页
    if ($page > 1) {
        $html .= '<a href="' . $url . '?page=' . ($page - 1) . '" class="prev">上一页</a>';
    }
    
    // 页码
    for ($i = 1; $i <= $total_page; $i++) {
        if ($i == $page) {
            $html .= '<span class="current">' . $i . '</span>';
        } else {
            $html .= '<a href="' . $url . '?page=' . $i . '">' . $i . '</a>';
        }
    }
    
    // 下一页
    if ($page < $total_page) {
        $html .= '<a href="' . $url . '?page=' . ($page + 1) . '" class="next">下一页</a>';
    }
    
    $html .= '</div>';
    return $html;
}
